<template>
    <div style="position : relative">
        <div :style="{height : '20px'}" />
        <el-row>
            <el-col :push="1" :span="22">
                <div>
                    <div>
                        <span class="right-align">
                            <el-button @click="dialogTitle = '发布新文章'; newArticle = true; rulesUpload = rulesUploadNew ;uploadDialogVisible = true" type="primary">新文章<i class="el-icon-upload el-icon--right"/></el-button>                            
                        </span>
                    </div>
                    <el-table
                    v-loading="dataLoading"
                    :data="tableData"
                    :style="{width: '100%',minHeight : '500px'}">

                        <el-table-column label="序号">
                            <template #default="scope">
                                <span v-text="scope.row.orderNo"/>
                            </template>
                        </el-table-column>

                        <el-table-column label="标题">
                            <template #default="scope">
                                <span v-text="scope.row.title"/>
                            </template>
                        </el-table-column>

                        <el-table-column label="创建日期">
                            <template #default="scope">
                                <span v-text="scope.row.createTime"/>
                            </template>
                        </el-table-column>

                        <el-table-column label="修改日期">
                            <template #default="scope">
                                <span v-if="scope.row.editTime != null" v-text="scope.row.editTime"/>
                                <span v-else v-text="'/'"/>
                            </template>
                        </el-table-column>
                        
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button
                                    size="mini"
                                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button
                                    size="mini"
                                    type="danger"
                                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                <el-button size="mini" type="info" @click="$router.push( '/article/' + scope.row.id);">预览</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                    
                </div>
            </el-col>
            <el-col :span="24">
                <div :style="{height : '120px'}"/>
                <el-pagination
                    class="centerBottom-position"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page.currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="page.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.totalItem">
                </el-pagination>
            </el-col>
        </el-row>
        
        

        <el-dialog 
            :title="dialogTitle" 
            v-model="uploadDialogVisible" 
            @closed="
                fileInfo = { 
                    title : '',
                    desc : '',
                    file : null
                };
                temp = null;
                newArticle = false;
                renewTableData();">
            <el-form ref="uploadForm" status-icon :model="fileInfo" :rules="rulesUpload" label-position="top">
                <el-form-item prop="title">
                    <el-divider content-position="left"><span class="divider-text">标题</span> </el-divider>
                    <el-input v-model="fileInfo.title" placeholder="请输入标题"/>
                </el-form-item>
                <el-form-item prop="desc">
                    <el-divider content-position="left"><span class="divider-text">简介</span> </el-divider>
                    <el-input type="textarea" v-model="fileInfo.desc" placeholder="文章简介"/>
                </el-form-item>
                <el-form-item prop="file">
                    <el-divider content-position="left"><span class="divider-text">正文</span></el-divider>
                    <input accept=".md" type="file" ref="articleFile" v-show="false" @change="fileInfo.file = $refs.articleFile.files[0]" />
                    <el-button v-if="!newArticle" @click="submitDownload(temp.id)">下载</el-button>
                    <el-button @click="$refs.articleFile.click()" type="primary">新文章<i class="el-icon-upload el-icon--right"/></el-button>
                    <span :style="{ display: 'inline-block', width : '20px'}" />
                    <span v-if="fileInfo.file!=null" v-text="fileInfo.file.name"/><span v-else v-text="'暂未选择文件'"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="uploadDialogVisible = false">取 消</el-button>
                <el-button type="primary" 
                    @click="uploadConfirm">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog
            v-model="deleteDialogVisible"
            @closed="
                temp = null;">
            <el-divider content-position="left"><span class="divider-text">警 告</span> </el-divider>
            是否确定删除
            <br>
            <span v-if="temp != null" v-text="temp.title"/>

            <template #footer>
                <span class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="danger"
                    @click="
                        submitDelete(temp.id);
                        deleteDialogVisible = false
                    ">确 定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<style lang="less" scoped>
.bottom-position {
    position: relative;
    bottom: 0px;
}
.right-align {
    position: relative;
    left: 90%;
}

.divider-text {
    font-size: 20px;
}
</style>

<script>
export default {
    name : "ManagementTable",
    created() {
        this.renewTableData();
    },
    computed: {
        articleUrl() {
            return this.$store.getters.getPathPrefix() + "article";
        },
        articleManagementUrl() {
            return this.$store.getters.getPathPrefix() + "management/article"
        },
        articleTableDataUrl() {
            return this.$store.getters.getPathPrefix() + "management/table-data";
        }
    },
    data() {
        var validateTitle = (rule, value, callback) => {
            if(value == "") {
                callback(new Error('请输入标题'));
            } else {
                callback();
            }
        };
        var validateDesc = (rule, value, callback) => {
            if(value == "") {
                callback(new Error('请输入简介'));
            } else {
                callback();
            }
        };
        var validateFile = (rule, value, callback) => {
            if(value == null) {
                callback(new Error('请选择文件'));
            } else {
                callback();
            }
        };
        return {
            temp : null,
            deleteDialogVisible : false,
            dialogTitle : '',
            newArticle : false,
            articleFileName : '',
            page : {
                currentPage : 1,
                totalItem : 0,
                pageSize : 5
            },
            dataLoading : false,
            tableData: [],
            uploadDialogVisible : false,
            fileInfo : { 
                title : "",
                desc : "",
                file : null
            },
            rulesUpload : null,
            rulesUploadNew : {
                title: [
                { validator: validateTitle, trigger: 'blur' }
                ],
                desc: [
                { validator: validateDesc, trigger: 'blur' }
                ],
                file: [
                    { validator: validateFile }
                ]
            },
            rulesUploadPut : {
                title: [
                { validator: validateTitle, trigger: 'blur' }
                ],
                desc: [
                { validator: validateDesc, trigger: 'blur' }
                ]
            },
        }
    },
    methods: {
        savaFile(data,name) {
            try {
                const blobUrl = window.URL.createObjectURL(data);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.download = name;
                a.href = blobUrl;
                a.click();
                
            } catch (e) {
                alert('保存文件出错');
            }
        },
        handleEdit(index, row) {
            this.temp = row;
            this.dialogTitle = '修改文章';
            this.fileInfo.title = this.temp.title;
            this.fileInfo.desc = this.temp.description;
            this.rulesUpload = this.rulesUploadPut;
            this.uploadDialogVisible = true;
        },
        handleDelete(index, row) {
            this.temp = row;
            this.deleteDialogVisible = true;
        },
        handleSizeChange(val) {
            this.page.pageSize = val;
            this.renewTableData();
        },
        handleCurrentChange(val) {
            this.page.currentPage = val;
            this.renewTableData();
        },
        submitDownload(id) {
            var url = this.articleUrl + '/' + id;
            var parmas = {};
            parmas.url = url;
            parmas.method = 'get';
            parmas.responseType = 'blob';
            this.$axios(parmas)
            .then(response => {
                if(response.data.flg == false) {
                    var msg = '下载失败!';
                    if(response.data.msg != null) {
                        msg = msg + ' ' + response.data.msg;
                    }
                    this.$message.error(msg);
                } else {
                    if(response.data == null) {
                        return;
                    }
                    let blob = new Blob([response.data]);
                    this.savaFile(blob,this.temp.title+".md");
                    this.$message({
                        message : '下载成功!',
                        type : 'success'
                    })
                    
                }
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        submitDelete(id) {
            var url = this.articleManagementUrl + '/' + id;
            this.$axios.delete(url)
            .then(response => {
                if(response.data.flg == true) {
                    this.renewTableData();
                    this.$message({
                        message : '删除成功!',
                        type : 'success'
                    })
                } else {
                    var msg = '删除失败!';
                    if(response.data.msg != null) {
                        msg = msg + ' ' + response.data.msg;
                    }
                    this.$message.error(msg);
                }
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        submitUpload(method) {
            var formData = new FormData()
            formData.append('title',this.fileInfo.title);
            formData.append('desc',this.fileInfo.desc);
            formData.append('file',this.fileInfo.file);
            //上传
            var parmas = {};
            parmas.url = this.articleManagementUrl;
            parmas.method = method;
            parmas.data = formData;
            if(method == 'put') {
                parmas.url = parmas.url + '/' + this.temp.id;
            }
            parmas.headers = { 'Content-Type': 'multipart/form-data;boundary='+  Math.floor(Math.random()*10000000) };
            this.$axios(parmas)
            .then(response => {// 成功的返回
                if(response.data.flg == true) {
                    this.$message({
                        message : '提交成功!',
                        type : 'success'
                    })
                    this.uploadDialogVisible = false;
                } else {
                    var msg = '提交失败!';
                    if(response.data.msg != null) {
                        msg = msg + ' ' + response.data.msg;
                    }
                    this.$message.error(msg);
                }
            }).catch(err => {// 失败的返回
                this.$message.error(err.message);
            });
            
        },
        uploadConfirm() {
            this.$refs.uploadForm.validate((valid) => {
                if (valid) {
                    this.submitUpload(this.newArticle ? 'post' : 'put');
                } else {
                    return false;
                }
            })
        },
        renewTableData() {
            var parmas = {};
            parmas.url = this.articleTableDataUrl + '/page-size/' + this.page.pageSize + '/page/' + this.page.currentPage;
            parmas.method = 'get';
            this.$axios(parmas)
            .then(response => {// 成功的返回
                if(response.data.flg == true) {
                    this.tableData = response.data.tableData;
                    this.page.totalItem = response.data.total;
                } else {
                    var msg = '列表信息获取失败!';
                    if(response.data.msg != null) {
                        msg = msg + ' ' + response.data.msg;
                    }
                    this.$message.error(msg);
                }
            }).catch(err => {// 失败的返回
                this.$message.error(err.message);
            });
        
        }
    }
}
</script>